<template>
  <div>
    <div class="query">
      <QueryForm :form="form" v-model="typeQuery" @handleQuery="handleQuery" />
    </div>

    <div class="table">
      <div class="action">
        <el-button type="primary" @click="handleAdd" v-has="'classification-add'">新增</el-button>
      </div>
      <el-table
        :data="typeList"
        border
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="cate_name" label="分类名称" align="center" />
        <el-table-column label="图片" align="center">
          <template #default="scope">
            <el-avatar
              shape="circle"
              size="large"
              :src="`${scope.row.cate_img}`"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag class="ml-2" :type="`${scope.row.state ? '' : 'danger'}`">{{
              scope.row.state ? "启用" : "禁用"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_time" label="创建时间" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click.prevent="handleEditor(scope.row)"
               v-has="'classification-edit'"
            >
              编辑
            </el-button>

            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="red"
              :title="`确定${scope.row.state === 1 ? '禁用' : '启用'}?`"
              @confirm="handleStateRow(scope.row)"
            >
              <template #reference>
                <el-button type="text" size="small" v-has="'classification-edit'">{{
                  scope.row.state === 1 ? "禁用" : "启用"
                }}</el-button>
              </template>
            </el-popconfirm>

            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="red"
              title="确定删除此分类?"
              @confirm="handledeleteRow(scope.row)"
            >
              <template #reference>
                <el-button type="text" size="small"  v-has="'classification-del'"> 删除 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next, jumper,total"
        :total="total"
        @current-change="handleCurrentChange"
        hide-on-single-page
      ></el-pagination>
    </div>

    <el-dialog
      v-model="dialogVisible"
      title="Tips"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        :rules="dataState.rules"
        :model="dataState.ruleForm"
        label-width="80px"
      >
        <div class="login-input">
          <el-form-item prop="cate_name" label="分类">
            <el-input
              placeholder="请输入分类名称"
              v-model="dataState.ruleForm.cate_name"
              clearable
            />
          </el-form-item>

          <el-form-item label="分类图片" prop="cate_img">
            <UploadImage
              :limit="1"
              v-model="dataState.ruleForm.cate_img"
              @change="validParams('cate_img')"
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleDetermine(ruleFormRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, nextTick } from "vue";
import { InfoFilled } from "@element-plus/icons-vue";
import { ElForm, ElMessage } from "element-plus";
import { classEdit, queryClassificationList } from "@/api/product";
import { classAdd, classDel, upload } from "@/api/product";
import UploadImage from "@/components/UploadImage.vue";

onMounted(() => {
  handleQuery();
});

type FormInstance = InstanceType<typeof ElForm>;
const ruleFormRef = ref<FormInstance | any>();

// 生成查询form结构数据
const form = [
  {
    type: "input",
    label: "分类名称",
    model: "cate_name",
    placeholder: "请输入分类名称",
  },
];

interface queryTy {
  page: number;
  limit: number;
  cate_name: string;
}
const typeQuery = ref({
  page: 1,
  limit: 10,
  cate_name: "",
});

const dataState = reactive(<any>{
  ruleForm: {
    cate_name: "",
    cate_img: "",
  },
  rules: {
    cate_name: [
      {
        required: true,
        message: "请输入分类名称",
        trigger: "blur",
      },
    ],
    cate_img: [
      {
        required: true,
        message: "请上传分类图片",
        trigger: "blur",
      },
    ],
  },
});

const action = ref("add");

// 新增编辑分类弹窗
const dialogVisible = ref<boolean>(false);

const validParams = (fieldName: String) => {
  ruleFormRef.value.validateField(fieldName, () => null);
};

const handleDetermine = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;
    const { cate_name } = dataState.ruleForm;
    interface Params {
      cate_name: string;
      cate_img: string;
    }
    const params: Params = {
      cate_name: cate_name,
      cate_img: dataState.ruleForm.cate_img,
    };
    console.log(params);
    let res: any;
    if (action.value === "add") {
      res = await classAdd(params);
    } else if (action.value === "edit") {
      res = await classEdit({ ...params, id: dataState.ruleForm.id });
    }
    if (res && res.code === 200) {
      ElMessage({ message: "更新成功", type: "success" });
      dialogVisible.value = false;
      handleReset(ruleFormRef);
      handleQuery();
    }
  });
};
// 分类列表
const typeList = ref([]);

// 表格tableLoading
const tableLoading = ref(false);

// 表格条数
const total = ref<number>(0);

const handleClose = () => {
  dialogVisible.value = false;
  handleReset(ruleFormRef);
};

// 重置
const handleReset = (form: any) => {
  form.value.resetFields();
};

const handleQuery = () => {
  // 查询
  console.log("handleQuery1");
  handleCurrentChange(1);
};

const handleAdd = () => {
  // 新增
  action.value = "add";
  dialogVisible.value = true;
};

const handleEditor = async (row: any) => {
  dialogVisible.value = true;
  action.value = "edit";
  // 表格编辑
  console.log("handleEditor", row);
  await nextTick();
  Object.assign(dataState.ruleForm, row);
};

// 启用禁用
const handleStateRow = async (row: any) => {
  const state = row.state == 1 ? 0 : 1;
  await classEdit({ id: row.id, state });
  ElMessage({ message: "更新成功", type: "success" });
  handleQuery();
};

// 删除
const handledeleteRow = async (row: any) => {
  await classDel({ id: row.id });
  ElMessage({ message: "更新成功", type: "success" });
  handleQuery();
};

// 表格分页
const handleCurrentChange = (currentPageNum: number) => {
  typeQuery.value.page = currentPageNum;
  handleGetTypeList();
};

// 获取list
const handleGetTypeList = () => {
  tableLoading.value = true;
  queryClassificationList(typeQuery.value).then((res: any) => {
    if (res.code === 200) {
      total.value = res.data.count;
      tableLoading.value = false;
      typeList.value = res.data.rows;
    }
  });
};
</script>

<style lang="scss">
.avatar {
  width: 148px;
  height: 148px;
  border-radius: 6px;
  display: block;
}
</style>
